import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { FetchService } from '../../../core/net/fetch.service';
import { GateControlDetailComponent } from './gate-control-detail/gate-control-detail.component';
import { GateJiezhiDetailComponent } from './gate-jiezhi-detail/gate-jiezhi-detail.component';
import * as _ from 'lodash';
import { HttpClient } from '@angular/common/http';
import { forkJoin } from 'rxjs';
import {
    GateSketchConfig,
    SectionConfig,
    GateSketchConfig1,
    GateSketchConfig2,
    SectionConfig168, SectionConfig169
} from './gate-sketch.config';

@Component({
    selector: 'app-gate-control-sketch',
    templateUrl: './gate-control-sketch.component.html',
    styleUrls: ['./gate-control-sketch.component.scss']
})
export class GateControlSketchComponent implements OnInit {
    userSectionId = JSON.parse(localStorage.getItem('userInfo'))['sectionId'];
    queryParamStationId;
    mngList = [];
    searchForm: FormGroup;
    gateList: Array<any> = [];
    sectionList: Array<any> = [];  //  断面
    sectionList1: Array<any> = [];  //  取水出水 断面
    controlList: Array<any> = [];
    tuishuiList: Array<any> = [];
    generalInfoList = [];

    sectionPosList = SectionConfig;
    activatedSectionName = '';
    radioMap = {
        '1': '宁西公司',
        '168': '跃进渠一所',
        '169': '跃进渠二所'
    };
    radioValue = '1';
    rtuUrl = (window as any).environment.rtuUrl;

    colorOptions = [
        { '0%': '#B7D1F6', '100%': '#B7D1F6' },
        { '0%': '#AB9AF7', '100%': '#AB9AF7' },
        { '0%': '#FDCF99', '100%': '#FDCF99' },
        { '0%': '#B7D1F6', '100%': '#B7D1F6' },
        { '0%': '#AB9AF7', '100%': '#AB9AF7' },
        { '0%': '#FDCF99', '100%': '#FDCF99' }
    ];
    colorOptions1 = [
        { '0%': '#FFB8A5', '100%': '#FFB8A5' },
        { '0%': '#9AC1F7', '100%': '#9AC1F7' },
        { '0%': '#FCAFCA', '100%': '#FCAFCA' },
        { '0%': '#FFB8A5', '100%': '#FFB8A5' },
        { '0%': '#9AC1F7', '100%': '#9AC1F7' },
        { '0%': '#FCAFCA', '100%': '#FCAFCA' }
    ];
    constructor(private fb: FormBuilder,
                private modalService: NzModalService,
                private http: HttpClient,
                private router: Router,
                private fetchService: FetchService) {
        this.searchForm = this.fb.group({
            watergateCode: [null]
            // sectionId: [null]
            // canalName: [null]
        });
    }

    ngOnInit(): void {
        this.getMngSelectionList().then(() => {
            if (this.userSectionId === '1') {
                this.queryInfo('0');
            } else {
                this.queryInfo(this.userSectionId);
            }
        });
    }

    /**
     * 获取管理单位列表 默认传入宁西公司id
     */
    getMngSelectionList(): Promise<any> {
        return new Promise(resolve => {
            this.fetchService
                .post('wrs/wrsBmanage/list', {
                    pid: '1',   //  宁西公司
                    // type: 2, //  管理所
                    pageSize: 10000
                })
                .subscribe(res => {
                    this.mngList = res['list'];
                    resolve();
                });
        });
    }

    queryInfo(radioValue): void {
        this.activatedSectionName = '';

        if (['168', '553', '554', '555', '556'].includes(radioValue)) {
            // 属于1所
            this.queryParamStationId = '168';
            this.sectionPosList = SectionConfig168;
        } else if (['169', '557', '558'].includes(radioValue)) {
            // 属于2所
            this.queryParamStationId = '169';
            this.sectionPosList = SectionConfig169;
        } else {
            this.queryParamStationId = '1';
            this.sectionPosList = SectionConfig;
        }
        const params = {
            ...this.searchForm.value,
            stationId: radioValue === '0' ? null : this.queryParamStationId
        };
        let gateSketchConfig;
        if (this.userSectionId === '1') {
            gateSketchConfig = GateSketchConfig;
        }
        if (this.queryParamStationId === '168') {
            gateSketchConfig = GateSketchConfig1;
        } else if (this.queryParamStationId === '169') {
            gateSketchConfig = GateSketchConfig2;
        }
        forkJoin(
            this.fetchService.post<any>('base/wrsBrwaterDam/queryDamInfoList', { ...params, pageSize: 10000 }),
            this.fetchService.post<Array<any>>('wrs/wrsBrcrossSection/info', params)
        ).subscribe(res => {
            this.gateList = res[0]['list'].map(gate => {
                return {
                    ...gate,
                    degreeRate: parseFloat(gate.degree) / parseFloat(gate.strobeOpenHeight) * 100
                };
            });
            const openedItems = this.gateList.filter(item => {
                return parseFloat(item.degree) > 0; //  闸门开度大于0即为开闸斗口
            });
            const onlineItems = this.gateList.filter(item => {
                return item.onlinestatus === 'on';
            });

            const warningLevel = 2;
            this.sectionList = [];
            res[1].forEach(item => {
                const level = parseFloat(item.shuiwei || '0') <= 0 ? 0 : parseFloat(item.shuiwei || '0');
                const gate = gateSketchConfig.find(config => {
                    return config.name === item.stationName;
                });
                if (gate) {
                    this.sectionList.push({
                        ...gate,
                        title: item.stationName,
                        level: item.shuiwei,
                        flow: item.shunshiliuliang,
                        percentage: level / warningLevel * 100,
                    });
                }

            });
            const specSectionList = [
                {
                    stationName: '取水断面'
                },
                {
                    stationName: '出水断面'
                }
            ];
            this.sectionList1 = [];
            specSectionList.forEach(item => {
                const gate = gateSketchConfig.find(config => {
                    return config.name === item.stationName;
                });
                if (gate) {
                    this.sectionList1.push({
                        title: item.stationName,
                        level: '--',
                        flow: '--',
                        percentage: 0,
                        top: gate.top,
                        left: gate.left
                    });
                }
            });
            this.generalInfoList = [
                {
                    name: '斗口数量',
                    num: this.gateList.length,
                    unit: '个'
                },
                {
                    name: '开闸斗口',
                    num: openedItems.length,
                    unit: '个'
                },
                {
                    name: '斗口在线',
                    num: onlineItems.length,
                    unit: '个'
                },
                {
                    name: '离线斗口',
                    num: this.gateList.length - onlineItems.length,
                    unit: '个'
                },
                {
                    name: '测流断面',
                    num: this.sectionList.length + this.sectionList1.length,
                    unit: '个'
                },
                {
                    name: '超警戒',
                    num: '-',
                    unit: '个'
                },
                {
                    name: '水位计',
                    num: '8',
                    unit: '个'
                }
            ];
        });

        this.fetchService.post('wrs/wrsBawaterGate/gateInfo', {
            // sectionId: this.radioValue === '0' ? null : this.radioValue
        }).subscribe(res => {
            if (res && Array.isArray(res)) {
                const actualList = res.filter(item => {
                    return gateSketchConfig.find(config => {
                        return config.name === item['watergateCode'];
                    });
                });
                const list = actualList.map(item => {
                    const gate = gateSketchConfig.find(config => {
                        return config.name === item['watergateCode'];
                    });
                    return {
                        ...item,
                        ...gate,
                        title: item['watergateCode'],
                        warningLevel: item['gateInfo'].filter(info => {
                            return _.endsWith(info.itemId, 'WaterLevel');
                        }).length ? item['gateInfo'].filter(info => {
                            return _.endsWith(info.itemId, 'WaterLevel');
                        })[0]['val'] : '--',
                        openInfo: item['gateInfo'].filter(info => {
                            return info.itemId.indexOf('Position') != -1;
                        })
                    };
                });
                this.controlList = list.filter(item => {
                    return item.type === 'jiezhizha';
                });
                this.tuishuiList = list.filter(item => {
                    return item.type === 'tuishuizha';
                });
            }
        });

    }

    sectionOnActivated(data): void {
        this.radioValue = null;
        this.activatedSectionName = data.name;
        this.fetchService.post<any>('base/wrsBrwaterDam/queryDamInfoList', {
            sectionId: data.sectionId,
            section2Id: data.section2Id,
            pageSize: 10000
        }).subscribe(res => {
            this.gateList = res['list'].map(gate => {
                return {
                    ...gate,
                    degreeRate: parseFloat(gate.degree) / parseFloat(gate.strobeOpenHeight) * 100
                };
            });
            const openedItems = this.gateList.filter(item => {
                return parseFloat(item.degree) > 0; //  闸门开度大于0即为开闸斗口
            });
            const onlineItems = this.gateList.filter(item => {
                return item.onlinestatus === 'on';
            });
            this.generalInfoList.forEach(item => {
                if (item.name === '斗口数量') {
                    item.num = this.gateList.length;
                }
                if (item.name === '开闸斗口') {
                    item.num = openedItems.length;
                }
                if (item.name === '斗口在线') {
                    item.num = onlineItems.length;
                }
                if (item.name === '离线斗口') {
                    item.num = this.gateList.length - onlineItems.length;
                }
            });
        });
    }

    openGateDetailModal(data): void {
        const modal = this.modalService.create({
            nzTitle: data.watergateCode,
            nzClassName: 'custom-modal',
            nzWidth: '90%',
            nzBodyStyle: {
                background: '#eee',
                margin: 0,
                padding: '5px'
            },
            nzContent: GateControlDetailComponent,
            nzFooter: null,
            nzComponentParams: {
                data: data
            }
        });
        modal.afterOpen.subscribe(() => console.log('[afterOpen] emitted!'));

        // Return a result when closed
        modal.afterClose.subscribe(result => console.log('[afterClose] The result is:', result));

        // delay until modal instance created
        // setTimeout(() => {
        //     const instance = modal.getContentComponent();
        //     instance.subtitle = 'sub title is changed';
        // }, 2000);
    }

    directToList(): void {
        this.router.navigate(['/gate/gt-control-list']);
    }

    //  节制闸弹窗
    openJieZhiDetailModal(data): void {
        const groupIndexArr = data['groupIndex'].split(',');
        if (groupIndexArr.length < 2) {
            this.http.post(`${ this.rtuUrl }data/view`, {
                groupIndex: data['groupIndex'],
                serverIndex: '0'
            }).subscribe(res => {
                const list = res['data'];
                const keysArr = list.map(item => {
                    return item['col'];
                });
                const valsArr = list.map(item => {
                    return item['val'];
                });
                const modal = this.modalService.create({
                    nzTitle: data['watergateCode'],
                    nzClassName: 'custom-modal',
                    nzWidth: 1598,
                    nzBodyStyle: {
                        background: '#eee',
                        margin: 0,
                        padding: '5px'
                    },
                    nzContent: GateJiezhiDetailComponent,
                    nzFooter: null,
                    nzComponentParams: {
                        dianbiaoData: _.zipObject(keysArr, valsArr),
                        dianbiaoData2: null,
                        jzData: data,
                        groupIndex: data['groupIndex']
                    }
                });
                modal.afterOpen.subscribe(() => console.log('[afterOpen] emitted!'));

                // Return a result when closed
                modal.afterClose.subscribe(result => console.log('[afterClose] The result is:', result));

            });
        } else {
            //  余丁 有6孔 需要分两组获取数据
            const yuding1 = this.http.post(`${ this.rtuUrl }data/view`, {
                groupIndex: '6',
                serverIndex: '0'
            });
            const yuding2 = this.http.post(`${ this.rtuUrl }data/view`, {
                groupIndex: '7',
                serverIndex: '0'
            });
            forkJoin(yuding1, yuding2).subscribe(res => {
                if (res) {
                    const list1 = res[0]['data'];
                    const list2 = res[1]['data'];
                    const keysArr1 = list1.map(item => {
                        return item['col'];
                    });
                    const valsArr1 = list1.map(item => {
                        return item['val'];
                    });
                    const keysArr2 = list2.map(item => {
                        return item['col'];
                    });
                    const valsArr2 = list2.map(item => {
                        return item['val'];
                    });
                    const modal = this.modalService.create({
                        nzTitle: data['watergateCode'],
                        nzClassName: 'custom-modal',
                        nzWidth: 1598,
                        nzBodyStyle: {
                            background: '#eee',
                            margin: 0,
                            padding: '5px'
                        },
                        nzContent: GateJiezhiDetailComponent,
                        nzFooter: null,
                        nzComponentParams: {
                            dianbiaoData: _.zipObject(keysArr1, valsArr1),
                            dianbiaoData2: _.zipObject(keysArr2, valsArr2),
                            jzData: data,
                            groupIndex: data['groupIndex']
                        }
                    });
                }
            });
        }

    }
}
